package dao.impl;

import dao.UserDao;
import pojo.User;
import service.UserService;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    @Override
    public List<User> findAll() {

        List<User> list = new ArrayList<>();


        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        //1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //创建连接
            String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
            connection = DriverManager.getConnection(url, "root", "Yan411328");
            if (connection != null) {
                System.out.println("连接成功");
            }
            //2.写sql
            String sql = "select * from user";

            //预编译sql
            preparedStatement = connection.prepareStatement(sql);

            //3.执行sql
            resultSet = preparedStatement.executeQuery();

            //4.遍历结果
            while (resultSet.next()) {
                User u = new User();
                u.setId(resultSet.getInt("id"));
                u.setName(resultSet.getString("name"));
                u.setPass(resultSet.getString("pass"));
                //
                list.add(u);
            }
            return list;

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {

            try {
                if (resultSet != null) {
                    resultSet.close();
                }

                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }


            } catch (SQLException e) {
                throw new RuntimeException(e);
            }



            //关闭资源


        }





        //TODO
    }
}
